package com.wsjc.common.redis.cluster;

import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;

import com.wsjc.common.core.config.JedisConfig;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 多主多从，hash-slot . redisCluster
 * 
 * @author 93733
 *
 */
public class JedisClusterInstance {

	@Autowired
	private static JedisPoolConfig jedisPoolConfig;

	private static JedisCluster jedisCluster;


	/**
	 * 获取jedis 实例
	 * 
	 * @param sentinelMaster
	 * @return
	 */
	public static JedisCluster newjedisClusterInstance() {

		Set<HostAndPort> set = new HashSet<HostAndPort>();

		// "127.0.0.1:6379;127.0.0.1:6380;127.0.0.1:6381" ;
		String jedisClusterNodes = JedisConfig.readConfig("jedis.cluster.nodes");

		String[] urls = jedisClusterNodes.split(";");
		for (String url : urls) {
			String[] serverInfo = url.split(":");
			String host = serverInfo[0];
			int port = Integer.parseInt(serverInfo[1]);
			HostAndPort hostAndPort = new HostAndPort(host, port);
			set.add(hostAndPort);
		}

		int connectionTimeout = Integer.valueOf(JedisConfig.readConfig("jedis.cluster.connection.timeout"));
		int soTimeout = Integer.valueOf(JedisConfig.readConfig("jedis.cluster.so.timeout"));
		int maxAttempts = Integer.valueOf(JedisConfig.readConfig("jedis.cluster.max.attempts"));
		String password = JedisConfig.readConfig("redis.auth.password");

		jedisCluster = new JedisCluster(set, connectionTimeout, soTimeout, maxAttempts, password, jedisPoolConfig);

		return jedisCluster;
	}

}
